using System;

namespace Pomelo.Protobuf
{
    public class Decoder
    {
        /// <summary>
        /// Decodes the UInt32.
        /// </summary>
    /*    public static uint decodeUInt32(int offset, byte[] bytes, out int length)
        {
            uint n = 0;
            length = 0;

            for (int i = offset; i < bytes.Length; i++)
            {
                length++;
                uint m = Convert.ToUInt32(bytes[i]);
                n = n + Convert.ToUInt32((m & 0x7f) * Math.Pow(2, (7 * (i - offset))));
                if (m < 128)
                {
                    break;
                }
            }

            return n;
        }*/

        public static ulong decodeVarint(int offset,byte[] bytes,out int length)
        {
            ulong n = 0;
            length = 0;
            int l = bytes.Length;
            int i = offset;
            for (int shift = 0;shift < 64;shift += 7)
            {
                if (i >= l)
                {
                    return n;
                }
                byte b = bytes[i];
                i++;
                length++;
                n |= (ulong)(b & 0x7F) << shift;
                if (b < 0x80)
                {
                    return n;
                }
            }
            return n;
        }

        public static uint decodeUInt32(int offset,byte[] bytes,out int length)
        {
            return (uint)decodeVarint(offset, bytes, out length);
        }

        /// <summary>
        /// Decodes the SInt32.
        /// </summary>
        public static int decodeSInt32(int offset, byte[] bytes, out int length)
        {
            return (int)decodeVarint(offset, bytes, out length);
            /*  uint n = decodeUInt32(bytes);
          //    int flag = ((n % 2) == 1) ? -1 : 1;

              int result = Convert.ToInt32(n);
              return result;*/
        }
    }
}